package spark.core.java;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

/**
 * 統計每行出現的次數
 */
public class LineCount {

    public static void main(String[] args) {
      //编写spark应用程序
        SparkConf conf = new SparkConf().setAppName("LocalFile").setMaster("local");
        JavaSparkContext sc = new JavaSparkContext(conf);
        JavaRDD<String> lines = sc.textFile("datas/hello.txt");


        //对LINES RDD 执行maptopair 算子，将每一行映射为（line,1）的这种key-value的格式
        //然后后面才能统计每一行出现的次数
       JavaPairRDD<String,Integer> pairs =  lines.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<String, Integer>(s, 1);
            }
        });

        //对pairs RDD执行reduceBykey算子，统计出每一行出现的总次数
        JavaPairRDD<String,Integer> lineCounts =  pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });

        //执行一个action操作，
        lineCounts.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            public void call(Tuple2<String, Integer> t) throws Exception {
                System.out.println(t._1()+" appears "+t._2() + " times.");
            }
        });

        sc.close();
    }
}
